<template>
  <div class="add_main_box">
    <el-dialog
      :key="generateId"
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      :title="isedit ? '编辑' + title : '添加' + title"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showDialog"
      width="750px"
      :before-close="handleClose2"
    >
      <div class="temp_select">
        <div class="temp_text">
          <span> 模板选择： </span>
          <el-select
            :disabled="isedit"
            style="width: 260px"
            v-model="mainForm.templateId"
            collapse-tags
            filterable
            placeholder="请选择"
            size="mini"
            value-key="token"
            @change="templateChange"
          >
            <el-option
              v-for="item in templateList"
              :key="item.token"
              :label="item.name + ' - ' + item.version"
              :value="item.id"
            >
              <!-- <span style="float: left">{{ item.name }}</span>
              <span style="color: #8492a6; font-size: 13px">{{
                item.version
              }}</span> -->
            </el-option>
          </el-select>
        </div>
      </div>
      <el-tabs
        v-model="activeName"
        :tab-position="tabPosition"
        class="tabHight tabHight_padding"
      >
        <el-tab-pane name="first" label="基础参数">
          <el-form
            class="tab_form"
            label-position="right"
            :model="mainForm"
            :rules="mainFormRules"
            ref="mainForm"
            size="mini"
            label-width="auto"
          >
            <el-row :gutter="16" type="flex">
              <!-- <el-col :span="12">
                <el-form-item label="名称:" prop="name">
                  <el-input
                    v-model="mainForm.name"
                    placeholder="请输入名称"
                  ></el-input>
                </el-form-item>
              </el-col> -->

              <el-col :span="12">
                <el-form-item label="零件号:" prop="partNumber">
                  <el-select
                    v-if="parAdditional('零件号').length"
                    v-model="mainForm.partNumber"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(mainForm.partNumber, '零件号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('零件号')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    @input="partInput(mainForm.partNumber, '零件号')"
                    v-model="mainForm.partNumber"
                    placeholder="请输入零件号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="零件名称:" prop="partName">
                  <el-select
                    v-if="parAdditional('零件名称').length"
                    v-model="mainForm.partName"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(mainForm.partName, '零件名称')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('零件名称')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    @input="partInput(mainForm.partName, '零件名称')"
                    v-model="mainForm.partName"
                    placeholder="请输入零件名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序号:" prop="processNumber">
                  <el-select
                    v-if="parAdditional('工序号').length"
                    v-model="mainForm.processNumber"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(mainForm.processNumber, '工序号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('工序号')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    @input="partInput(mainForm.processNumber, '工序号')"
                    v-model="mainForm.processNumber"
                    placeholder="请输入工序号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序名称:" prop="processName">
                  <el-select
                    v-if="parAdditional('工序名称').length"
                    v-model="mainForm.processName"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(mainForm.processName, '工序名称')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('工序名称')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    @input="partInput(mainForm.processName, '工序名称')"
                    v-model="mainForm.processName"
                    placeholder="请输入工序名称"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12" v-if="isedit">
                <el-form-item label="作者:" prop="author">
                  <el-input disabled v-model="mainForm.author"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工艺版次:" prop="version">
                  <el-input
                    :disabled="isedit"
                    v-model="mainForm.version"
                    placeholder="请输入工艺版次"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="状态:" prop="state">
                  <el-radio v-model="mainForm.state" label="true"
                    >可用</el-radio
                  >
                  <el-radio v-model="mainForm.state" label="false"
                    >禁用</el-radio
                  >
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="有效期:">
                  <!-- <span slot="label">
                    <el-checkbox v-model="mainForm.isTermValidity" label="true"
                      >有效期:</el-checkbox
                    >
                  </span> -->
                  <el-date-picker
                    v-model="mainForm.youxiaoqi"
                    type="datetimerange"
                    format="yyyy 年 MM 月 dd 日"
                    class="w100"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                  <!-- <el-date-picker
                    v-model="mainForm.youxiaoqi"
                    class="w100"
                    type="date"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker> -->
                </el-form-item>
              </el-col>
              <div class="line_box"></div>
              <el-col
                :span="12"
                v-for="item in technologyParameter"
                :key="item.key"
              >
                <el-form-item
                  :label="item.key + ':'"
                  v-if="
                    !sparePartsList.includes(item.key) &&
                    item.type != 5 &&
                    item.type != 6
                  "
                >
                  <el-select
                    v-if="item.additional.length"
                    v-model="item.val"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    :disabled="item.disabled"
                    class="w100"
                  >
                    <el-option
                      v-for="item in item.additional"
                      :key="item.value"
                      :label="item.text"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    :disabled="item.disabled"
                    v-model="item.val"
                    :placeholder="item.value"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <!-- <el-tab-pane name="three" label="元数据">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
            ref="metaDataRef"
          />
        </el-tab-pane> -->
      </el-tabs>
      <div slot="footer" class="dialog-footer" v-if="isedit">
        <el-button
          :loading="btnLoading"
          size="mini"
          @click="handleCloseBtn(false)"
          >取 消</el-button
        >
        <el-button
          v-permission="[3, 'button']"
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('mainForm')"
          >确 定</el-button
        >
        <el-button
          v-permission="[3, 'button']"
          :loading="btnLoading"
          size="mini"
          type="success"
          @click="submitFormNext('mainForm')"
          >保存并继续</el-button
        >
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button
          :loading="btnLoading"
          size="mini"
          @click="handleCloseBtn(false)"
          >取 消</el-button
        >
        <el-button
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('mainForm')"
          >确 定</el-button
        >
        <el-button
          :loading="btnLoading"
          size="mini"
          type="success"
          @click="submitFormNext('mainForm')"
          >保存并继续</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { spareParts } from "@/utils/local";
// const spareParts = [
//   "零件号",
//   "工序号",
//   "工步号",
//   "工步名称",
//   "零件名称",
//   "工序名称",
// ];
// import MetaData from "@/views/opensite/metaData.vue";
import {
  getTemplate,
  submitTechnology,
  getTechnologyToken,
  submitTechnologyPut,
  save2pdf,
} from "@/api/technology";
import { generateId } from "@/utils/index";
// import { useExecl } from "./js/index";
import { mapGetters } from "vuex";
import { VERSION_RULES } from "@/utils/local";
export default {
  components: {
    // MetaData,
  },
  props: {
    mainToken: {
      type: String,
      default: "",
    },
    showDialog: {
      type: Boolean,
      default: true,
    },
    isedit: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      sparePartsList: spareParts,
      additional: [],
      btnLoading: false,
      technologyParameter: [],
      activeName: "first",
      // showDialog: false,
      tabPosition: "left",
      deviceTypeData: [],
      editmetaData: {},
      editCustomData: [],
      deviceTypeIds: "",
      selectedTemplateData: "",
      templateList: [],
      mainForm: {
        partNumber: "",
        partName: "",
        processNumber: "",
        processName: "",
        youxiaoqi: "",
        isTermValidity: false,

        technologyParameter: [],
        name: "",
        state: "true",
        templateId: "",
        metadata: {},
        url: "",
        author: "",
        version: "",
        token: "",
        startDate: "",
        endDate: "",
      },
      cloneVersion: "",
      mainFormRules: {
        processNumber: [
          { required: true, message: "请输入工序号", trigger: "blur" },
        ],
        processName: [
          { required: true, message: "请输入工序名称", trigger: "blur" },
        ],
        state: [{ required: true, message: "请选择状态", trigger: "blur" }],
        version: VERSION_RULES,
        partNumber: [
          { required: true, message: "请输入零件号", trigger: "blur" },
        ],
        partName: [
          { required: true, message: "请输入零件名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {},
  computed: {
    ...mapGetters(["tenant"]),
    // username() {
    //   return getCookie("user").username;
    // },
    parAdditional() {
      return function (key = "零件号") {
        const obj = this.technologyParameter.find((item) => {
          return item.key == key && item.additional.length !== 0;
        });
        return obj?.additional || [];
      };
    },

    username() {
      return this.$store.state.user.user.username;
    },
    generateId() {
      return generateId();
    },
  },
  watch: {
    // showDialog(newValue, oldValue) {
    //   this.showDialog = newValue;
    // },
  },
  methods: {
    // 弹窗关闭执行操作
    handleClose2(done) {
      if (this.btnLoading) {
        return;
      } else {
        done();
      }
    },
    handleCloseBtn() {
      if (this.btnLoading) {
        return;
      } else {
        this.handleClose();
      }
    },
    partInput(val, key) {
      this.technologyParameter.forEach((item) => {
        if (item.key == key) {
          item.val = val;
        }
      });
    },
    //弹窗打开执行操作
    handleOpen() {
      this.mainForm.author = this.username;
      this.getTemplateList();
      if (this.isedit) {
        this.getMainData();
      } else {
      }
      this.$nextTick(() => {
        //   this.$refs["mainForm"].resetFields();
        this.$refs["mainForm"].clearValidate();
      });
    },
    //获取主工艺数据 (详情)
    getMainData() {
      getTechnologyToken(this.mainToken).then((res) => {
        const { data } = res;
        const { metadata, technologyParameter, technologyTemplate } = data;
        technologyParameter.forEach((item) => {
          technologyTemplate.technologyParameter.forEach((ele) => {
            if (item.key == ele.key) {
              this.$set(item, "additional", ele.additional);
            }
          });
        });
        this.technologyParameter = technologyParameter.map((item) => {
          return {
            ...item,
            v: item.value,
            val: item.value,
            disabled: spareParts.includes(item.key),
          };
        });
        this.$nextTick(() => {
          this.mainForm = {
            ...data,
            youxiaoqi: [data.startDate, data.endDate],
          };
          this.cloneVersion = data.version;
          // this.editmetaData = metadata;
        });
      });
    },
    //获取模板列表
    getTemplateList() {
      var params = {
        page: 1,
        pageSize: 0,
      };
      getTemplate(params).then((res) => {
        const { results } = res.data;
        console.log(res, "模板", this.mainForm.version);
        this.templateList = results;
      });
    },

    //模板选择
    templateChange(val) {
      const obj = this.templateList.find((item) => item.id == val);
      console.log("obj :>> ", obj);
      this.mainForm.reportId = obj.reportId;
      // this.mainForm.version = obj.version;
      // mainForm.partNumber
      this.technologyParameter = obj.technologyParameter.map((item) => {
        let val = "";
        spareParts.forEach((spa) => {
          if (spa == item.key) {
            val = this.mainForm.partNumber;
          }
        });
        // if (item.key == spareParts[0]) {
        //   val = this.mainForm.partNumber;
        // }
        // if (item.key == spareParts[1]) {
        //   val = this.mainForm.processNumber;
        // }

        return {
          ...item,
          v: item.key,
          val: val,
          disabled: spareParts.includes(item.key),
        };
      });
      // this.additional = this.templateChange.additional;
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh, token) {
      // this.showDialog = false;
      this.$emit("update:showDialog", false);
      this.$emit("closeDialog", isRefresh, token);
      this.cancelEmpty();
    },
    //取消清空数据
    cancelEmpty() {
      // this.mainForm = {};
      this.$nextTick(() => {
        Object.assign(this.$data.mainForm, this.$options.data().mainForm);
        this.mainForm.version = "";
        this.technologyParameter = [];
        // this.$refs.metaDataRef.clearMeteDada();
        // this.$refs["mainForm"].resetFields();
        // this.$refs["mainForm"].clearValidate();
      });

      this.activeName = "first";
    },
    async submitFormNext(formName) {
      if (this.$store.getters["user/isNavTo"](15)) {
        const res = await this.submitForm(formName, true);
      } else {
        this.$msg("您没有设备工艺配方的相关权限");
      }
    },
    // 提交
    async submitForm(formName, isNext = false) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (!this.mainForm.templateId) {
            this.$msg("请选择模板");
            return;
          }
          this.btnLoading = true;
          // processNumber processNumber
          const fileName = `${this.tenant.token}/technology/xls/${
            this.mainForm.partNumber +
            "_" +
            this.mainForm.processNumber +
            "_" +
            this.mainForm.version
          }.xlsx`;
          console.log("fileName :>> ", fileName);
          try {
            this.mainForm.technologyParameter = this.technologyParameter.map(
              (item) => {
                return {
                  ...item,
                  value: item.val,
                  text: item.val,
                };
              }
            );
            // useExecl(
            //   this.mainForm.url,
            //   this.mainForm.technologyParameter,
            //   fileName
            // )
            //   .then((url) => {
            // this.mainForm.url = url;
            this.mainForm.startDate = this.mainForm.youxiaoqi[0];
            this.mainForm.endDate = this.mainForm.youxiaoqi[1];
            this.btnLoading = true;

            //  零件号 工序号拼接token
            this.mainForm.token =
              this.mainForm.partNumber +
              "_" +
              this.mainForm.processNumber +
              "_" +
              this.mainForm.version;
            // this.mainForm.partNumber+'_'+this.mainForm.specificationNumber
            console.log("this.mainForm :>> ", this.mainForm);
            if (this.isedit) {
              submitTechnologyPut(this.mainForm, this.mainToken)
                .then(async (res) => {
                  // await save2pdf(url);
                  this.btnLoading = false;
                  console.log(res, "提交成功");
                  if (isNext) {
                    this.$router.push({
                      name: "recipeList",
                      params: {
                        technologyFrom: JSON.stringify(res.data),
                      },
                    });
                  } else {
                    this.handleClose(true, res.data.token);
                  }
                  this.$msg({
                    type: "success",
                    message: "修改成功",
                  });
                })
                .finally((f) => {
                  this.btnLoading = false;
                });
            } else {
              submitTechnology(this.mainForm)
                .then(async (res) => {
                  // console.log(res, "提交成功");
                  // this.handleClose(true);
                  // await save2pdf(url);
                  this.btnLoading = false;
                  if (isNext) {
                    this.$router.push({
                      name: "recipeList",
                      params: {
                        technologyFrom: JSON.stringify(res.data),
                      },
                    });
                  } else {
                    this.handleClose(true);
                  }
                  this.$msg({
                    type: "success",
                    message: "添加成功",
                  });
                })
                .finally((f) => {
                  this.btnLoading = false;
                });
            }
            // })
          } catch (error) {
            this.btnLoading = false;
          }
        }
      });
    },
    //元数据页回传
    sendmetaData(data) {
      this.mainForm.metadata = data;
    },
    sendCustomDatas(data) {
      this.mainForm.mainTechnologies = data;
    },
    sendRecipeDatas(data) {
      this.mainForm.technologyFormulas = data;
    },
  },
};
</script>

<style lang='scss' scoped>
.line_box {
  width: 100%;
  height: 1px;
  background: #dcdfe6;
  margin-bottom: 15px;
}
.add_main_box {
  /deep/ .el-dialog__body {
    padding-top: 0;
    padding-left: 0;
    padding-right: 0;
  }
}
.tab_form {
  margin-right: 15px;
  max-height: calc(50vh);
  overflow: hidden;
  overflow-y: auto;
  padding-right: 10px;
  /* padding-right: 10px; */
  /deep/ .el-row--flex {
    flex-wrap: wrap;
  }
}
.tabHight_padding {
  padding: 15px;
  /* height: calc(100vh - 400px); */
}
.temp_select {
  height: 56px;
  background: #f9f9f9;
  width: 100%;

  display: flex;
  align-items: center;
  padding-left: 50px;
}
.temp_text {
  display: flex;
  align-items: center;
  /* font-family: Microsoft YaHei; */
  /* line-height: 22px; */
  color: #333333;
  /* position: absolute; */
  /* margin: 14px 0 0 60px; */
}
</style>
